﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace GameControlTest
{
    public partial class GameControlDispatcherTimer : UserControl
    {
        private List<CompositeTransform> _rectTransforms;
        private DispatcherTimer _dt;
        private DateTime _lastTime;

        private static Random s_random = new Random();

        public GameControlDispatcherTimer()
        {
            InitializeComponent();

            _rectTransforms = new List<CompositeTransform>();

            for (int i = 0; i < App.ObjectCount; i++)
            {
                Rectangle r = new Rectangle();
                r.Width = 40;
                r.Height = 40;
                r.Fill = new SolidColorBrush(Color.FromArgb(255, (byte)s_random.Next(256),
                    (byte)s_random.Next(256), (byte)s_random.Next(256)));
                CompositeTransform ct = new CompositeTransform();
                ct.TranslateX = s_random.Next(800) - 400;
                ct.TranslateY = s_random.Next(600) - 300;
                r.RenderTransform = ct;
                _rectTransforms.Add(ct);
                this.LayoutRoot.Children.Add(r);
            }

            _lastTime = DateTime.Now;

            _dt = new DispatcherTimer();
            _dt.Interval = TimeSpan.Zero;
            _dt.Tick += new EventHandler(_dt_Tick);
            _dt.Start();
        }

        private void _dt_Tick(object sender, EventArgs e)
        {
            DateTime now = DateTime.Now;
            TimeSpan elapsedTime = now - _lastTime;
            _lastTime = now;
            float elapsedTimeRatio = (float)elapsedTime.TotalSeconds / ((float)60 / 1000);

            System.Threading.Thread.Sleep(App.Sleep);
            foreach (CompositeTransform ct in _rectTransforms)
            {
                //ct.TranslateX = s_random.Next(800) - 400;
                //ct.TranslateY = s_random.Next(600) - 300;
                ct.TranslateX += elapsedTimeRatio;
                ct.TranslateY += elapsedTimeRatio;
            }
        }
    }
}
